<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Debugger Demo</title>
  <script src="bin/debugger.js"></script>
  <script>
let index = 0;
let surface;

DebuggerInit({
  locateFile: (file) => '/node_modules/debugger/bin/'+file,
}).then((Debugger) => {
  const player = new Debugger.SkpDebugPlayer();

  // Define an event handler for the file input dialog
  function readSkpFile(e){
    // Did the change event result in the file-input element specifing a file? (user might have cancelled the dialog)
    const file = e.target.files[0];
    if (!file) {
      return;
    }
    // create a callback for when the file finishes being read.
    const reader = new FileReader();
    reader.onload = function(e) {
      // Convert e.target.result (an ArrayBuffer) into a typedarray,
      // otherwise fileMem.set() below seems to have no effect.
      const fileContents = new Uint8Array(e.target.result);
      const size = fileContents.byteLength;
      // Allocate memory in wasm to hold the skp file selected by the user.
      const fileMemPtr = Debugger._malloc(size);
      // Make a typed array view of that memory
      let fileMem = new Uint8Array(Debugger.HEAPU8.buffer, fileMemPtr, size);
      // Copy the file into it
      fileMem.set(fileContents);
      // Hand off pointer to wasm
      player.loadSkp(fileMemPtr, size);
      // From the loaded commands, Debugger now knows the bounds.
      let bounds = player.getBounds();
      // Resize our canvas to match
      canvas = document.getElementById('debugger_view');
      canvas.width = bounds.fRight - bounds.fLeft;
      canvas.height = bounds.fBottom - bounds.fTop;
      //Assume GPU selected initially
      surface = Debugger.MakeWebGLCanvasSurface(canvas);

      document.getElementById('command-count').innerHTML = player.getSize();
      player.setClipVizColor(0);
    };
    reader.readAsArrayBuffer(file);
  }

  function playFile() {
    interval = parseFloat(document.getElementById('interval').value);
    let intervalID = setInterval(function() {
        if (index < 789){
          player.drawTo(surface, index);
          surface.flush();
          index++;
        }
    }, interval);
  }

  // Discard canvas when switching between cpu/gpu backend because it's bound to a context.
  function replaceCanvas() {
      canvas = document.getElementById('debugger_view');
      let newCanvas = canvas.cloneNode(true);
      let parent = canvas.parentNode;
      parent.replaceChild(newCanvas, canvas);
  }

  document.getElementById('file-input')
    .addEventListener('change', readSkpFile);

  document.getElementById('play_button')
    .addEventListener('click', playFile);

  document.getElementById('overdraw')
    .addEventListener('change', function(e) {
      player.setOverdrawVis(e.target.checked);
    });

  document.getElementById('gpu_op_bounds')
    .addEventListener('change', function(e) {
      player.setGpuOpBounds(e.target.checked);
    });

  document.getElementById('clip_viz_color')
    .addEventListener('change', function(e) {
      // Remove the '#' from the hex color string.
      // prepend an alpha value (0x50 or about 30%)
      // then convert to an integer.
      colorInt = parseInt("50"+e.target.value.substring(1),16);
      player.setClipVizColor(colorInt);
    });

  document.getElementById('disable_clip_viz')
    .addEventListener('click', function(e) {
      // Setting the clip viz to transparent black makes it invisible.
      player.setClipVizColor(0);
    });

  document.getElementById('get_json_command_list')
    .addEventListener('click', function(e) {
      result = player.jsonCommandList(surface);
      console.log('getjsoncommandlist result '+result.substring(0,100)+'...');
      commands = JSON.parse(result);
      console.log('parsed json');
    });

  document.getElementById('backend_gpu')
    .addEventListener('change', function(e) {
      if (e.target.checked) {
        replaceCanvas();
        surface = Debugger.MakeWebGLCanvasSurface(document.getElementById('debugger_view'));
      }
    });

  document.getElementById('backend_cpu')
    .addEventListener('change', function(e) {
      if (e.target.checked) {
        replaceCanvas();
        surface = Debugger.MakeSWCanvasSurface(document.getElementById('debugger_view'));
      }
    });

});
  </script>
  </head>
  <body>
    <canvas id=debugger_view width=400 height=400></canvas>
    <div style="float:right">
      <input type="radio" name="backend" value="CPU" id="backend_cpu"> CPU
      <input type="radio" name="backend" value="WebGL" id="backend_gpu" checked> WebGL<br>
      <input type="file" id="file-input" /> | <span id="command-count">0</span> commands<br>
      <input type="button" id="play_button" value="Play" />
      command interval in ms
      <input type="text" id="interval" value="20" /><br>
      <input type="checkbox" id="overdraw" /> Overdraw vis<br>
      <input type="checkbox" id="gpu_op_bounds" /> GPU Op bounds<br>
      <input type="color" id="clip_viz_color" />Clip visualization color
      <input type="button" id="disable_clip_viz" value="Disable" /><br>
      <input type="button" id="get_json_command_list" value="Get JSON Command List" /><br>
    <div>
    <div style="float:clear"></div>
  </body>
</html>
